package com.wondedDream.service.impl;

import cn.hutool.json.JSONObject;
import com.wondedDream.jwt.JwtUtils;
import com.wondedDream.model.PhoneNumber;
import com.wondedDream.model.User;
import com.wondedDream.repository.PhoneNumberRepository;
import com.wondedDream.repository.UserRepository;
import com.wondedDream.service.UserService;
import com.wondedDream.util.DecryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
//    @Autowired
//    private UserDetailsService userDetailsService;
    @Autowired
    private PhoneNumberRepository phoneNumberRepository;
    @Autowired
    private RestTemplate restTemplate;@Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private AuthenticationManager authenticationManager;


    private static final String WECHAT_APPID = System.getProperty("wechat.appid");
    private static final String WECHAT_SECRET = System.getProperty("wechat.secret");
    private static final String WECHAT_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=";

    @Override
    public User saveUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public User getUserById(Integer id) {
        return userRepository.findById(id).orElse(null);
    }

    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @Override
    public User saveOrUpdateUser(User user) {
        return userRepository.saveAndFlush(user);
    }

    @Override
    public JSONObject login(String code, String encryptedData, String iv) {
        /*
        // 使用 code 从微信服务器获取 openid 和 session_key
        String url = WECHAT_URL + WECHAT_APPID + "&secret=" + WECHAT_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        WeChatSession weChatSession = restTemplate.getForObject(url, WeChatSession.class);
        if (weChatSession == null || weChatSession.getOpenid() == null) {
            return "获取微信信息失败";
        }

        // 检查用户是否存在
        User user = userRepository.findByOpenid(weChatSession.getOpenid());
        if (user == null) {
            // 用户不存在，创建新用户
            user = new User();
            user.setOpenid(weChatSession.getOpenid());
        }

        // 解密 encryptedData 以获取手机号
        String phoneNumber = decryptPhoneNumber(weChatSession.getSession_key(), encryptedData, iv);
        if (phoneNumber == null) {
            return "无法获取手机号";
        }

        // 保存或更新用户手机号
        user.setPhoneNumber(phoneNumber);
        userRepository.save(user);
        // 登录验证
        String s = validateLogin(phoneNumber);
        if(!"success".equals(s)){
            return s;
        }
        // 生成 JWT 并返回
        String token = jwtUtils.generateToken(weChatSession.getOpenid());*/
//
        String token = jwtUtils.generateToken("17600224445");

        JSONObject result = new JSONObject();
        result.put("userName", encryptedData);
        result.put("userCode", code);
        result.put("accessToken", token);
        return result;

    }
    private String validateLogin(String phoneNumber) {
        Optional<PhoneNumber> phoneNumberEntity = Optional.ofNullable(phoneNumberRepository.findByPhoneNumber(phoneNumber));
        if (!phoneNumberEntity.isPresent()) {
            return "手机号未授权";
        }
        PhoneNumber phoneNumberObj = phoneNumberEntity.get();
        Date now = new Date();
        if (phoneNumberObj.getExpirationDate().before(now)) {
            return "手机号已过期";
        }
        return "success";
    }
    private Date calculateExpirationDate() {
        long oneYearInMillis = TimeUnit.DAYS.toMillis(365);
        return new Date(System.currentTimeMillis() + oneYearInMillis);
    }

    private String decryptPhoneNumber(String sessionKey, String encryptedData, String iv) {
        // 这里需要使用微信提供的解密算法，以下是一个简单示例，实际需要根据微信的算法实现
        // 可使用第三方库，如 Hutool 或自行实现 AES 解密
        return DecryptUtils.decryptPhoneNumber(sessionKey, encryptedData, iv);
    }

    // 内部类，用于解析微信返回的信息
    private static class WeChatSession {
        private String openid;
        private String session_key;

        public String getOpenid() {
            return openid;
        }

        public void setOpenid(String openid) {
            this.openid = openid;
        }

        public String getSession_key() {
            return session_key;
        }

        public void setSession_key(String session_key) {
            this.session_key = session_key;
        }
    }



}